Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.
In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.

The project is broken down into multiple steps:
We'll lead you through each part which you'll implement in Python.
When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.
To ensure we can download the latest version of the oxford_flowers102 dataset, let's first install both tensorflow-datasets and tfds-nightly.
tensorflow-datasets is the stable version that is released on a cadence of every few monthstfds-nightly is released every day and has the latest version of the datasetsWe'll also upgrade TensorFlow to ensure we have a version that is compatible with the latest version of the dataset.
#The new version of dataset is only available in the tfds-nightly package.
%pip --no-cache-dir install tfds-nightly --user
!pip install tensorflow --upgrade --user
After the above installations have finished be sure to restart the kernel. You can do this by going to Kernel > Restart.
# Import TensorFlow
import tensorflow as tf
import tensorflow_datasets as tfds
import tensorflow_hub as hub
# Ignore some warnings that are not relevant (you can remove this if you prefer)
import warnings
warnings.filterwarnings('ignore')
# TODO: Make all other necessary imports.
import matplotlib.pyplot as plt
import json
import tensorflow_hub as hub
import numpy as np
from PIL import Image
Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.
The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.
# Some other recommended settings:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
tfds.disable_progress_bar()
# Load the Oxford Flowers-102 dataset
(train_dataset, test_dataset, validation_dataset), dataset_info = tfds.load(
'oxford_flowers102',
split=['train', 'test', 'validation'],
shuffle_files=True,
with_info=True,
as_supervised=True
)
# Function to normalize and resize images
def preprocess_image(image, label):
# Normalize pixels to the range [0, 1]
image = tf.cast(image, tf.float32) / 255.0
# Resize images to 224x224 pixels
image = tf.image.resize(image, (224, 224))
return image, label
# Apply preprocessing to the datasets
train_dataset = train_dataset.map(preprocess_image)
test_dataset = test_dataset.map(preprocess_image)
validation_dataset = validation_dataset.map(preprocess_image)
# Shuffle and batch the datasets
train_dataset = train_dataset.shuffle(1024).batch(32).prefetch(tf.data.AUTOTUNE)
test_dataset = test_dataset.batch(32).prefetch(tf.data.AUTOTUNE)
validation_dataset = validation_dataset.batch(32).prefetch(tf.data.AUTOTUNE)
# Load the Oxford Flowers-102 dataset
dataset, dataset_info = tfds.load('oxford_flowers102', split='train', shuffle_files=True, with_info=True)
# Get the number of classes in the dataset
num_classes = dataset_info.features['label'].num_classes
# Get the class names
class_names = dataset_info.features['label'].names
# Display some sample images from the dataset
fig, axs = plt.subplots(3, 3, figsize=(10, 10))
fig.suptitle('Sample Images from Oxford Flowers-102 Dataset')
for i, data in enumerate(dataset.take(9)):
image = data['image']
label = data['label']
row = i // 3
col = i % 3
axs[row, col].imshow(image)
axs[row, col].set_title(class_names[label.numpy()])
axs[row, col].axis('off')
plt.show()
!pip install jinja2
# TODO: Print the shape and corresponding label of 3 images in the training set.
# TODO: Print the shape and corresponding label of 3 images in the training set.
counter = 0
for data in dataset.take(3):
image = data['image']
label = data['label']
print(f"Image shape: {image.shape}, Label: {class_names[label.numpy()]}")
counter += 1
if counter == 3:
break
# TODO: Plot 1 image from the training set.
# Set the title of the plot to the corresponding image label.
# Plot one image from the training set
for data in dataset.take(1):
image = data['image']
label = data['label']
plt.imshow(image)
plt.title(class_names[label])
plt.axis('off')
plt.show()
You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.
# Read the label mapping from the JSON file
with open('label_map.json', 'r') as file:
label_map = json.load(file)
# Print the label mapping
print(label_map)
# TODO: Plot 1 image from the training set. Set the title
# of the plot to the corresponding class name.
# Plot one image from the training set
for data in dataset.take(1):
image = data['image']
label = data['label']
plt.imshow(image)
plt.title(label_map[str(label.numpy())])
plt.axis('off')
plt.show()
# Define the batch size and image size
batch_size = 32
image_size = (224, 224)
# Load the Oxford Flowers-102 dataset
train_dataset, test_dataset, validation_dataset = tfds.load(
'oxford_flowers102',
split=['train', 'test', 'validation'],
shuffle_files=True,
as_supervised=True
)
# Function to preprocess the images
def preprocess_image(image, label):
# Normalize pixels to the range [0, 1]
image = tf.cast(image, tf.float32) / 255.0
# Resize images to the desired size
image = tf.image.resize(image, image_size)
return image, label
# Apply preprocessing and batching to the train, test, and validation datasets
train_dataset = train_dataset.map(preprocess_image).batch(batch_size).prefetch(tf.data.AUTOTUNE)
test_dataset = test_dataset.map(preprocess_image).batch(batch_size).prefetch(tf.data.AUTOTUNE)
validation_dataset = validation_dataset.map(preprocess_image).batch(batch_size).prefetch(tf.data.AUTOTUNE)
Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.
We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!
Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:
We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!
When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.
Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.
# Load the MobileNet pre-trained network from TensorFlow Hub
mobilenet_model = tf.keras.Sequential([
hub.KerasLayer("https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4",
input_shape=(224, 224, 3),
trainable=False)
])
# Define a new, untrained feed-forward network as a classifier
model = tf.keras.Sequential([
mobilenet_model,
tf.keras.layers.Dense(102, activation='softmax')
])
# Compile the model
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
# Train the classifier
history = model.fit(train_dataset,
epochs=10,
validation_data=validation_dataset)
# TODO: Plot the loss and accuracy values achieved during training for the training and validation set.
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
plt.figure(figsize=(8, 8))
plt.subplot(2, 1, 1)
plt.plot(acc, label='Training Accuracy')
plt.plot(val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.ylabel('Accuracy')
plt.ylim([min(plt.ylim()), 1])
plt.title('Training and Validation Accuracy')
plt.subplot(2, 1, 2)
plt.plot(loss, label='Training Loss')
plt.plot(val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.ylabel('Cross Entropy')
plt.ylim([0, max(plt.ylim())])
plt.title('Training and Validation Loss')
plt.xlabel('epoch')
plt.show()
It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.
# Evaluate the model on the test dataset
test_loss, test_accuracy = model.evaluate(test_dataset)
print(f'Test Loss: {test_loss:.4f}')
print(f'Test Accuracy: {test_accuracy:.4f}')
Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).
# TODO: Save your trained model as a Keras model
model_filepath = './my_model.h5'
# model.save(saved_keras_model_filepath)
model.save(model_filepath)
Load the Keras model you saved above.
# TODO: Load the Keras model
reloaded_keras_model = tf.keras.models.load_model(model_filepath, custom_objects={'KerasLayer':hub.KerasLayer})
reloaded_keras_model.summary()
Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:
probs, classes = predict(image_path, model, top_k)
If top_k=5 the output of the predict function should be something like this:
probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]
> ['70', '3', '45', '62', '55']
Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.
The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.
The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).
First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.
Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.
Finally, convert your image back to a NumPy array using the .numpy() method.
# TODO: Create the process_image function
def preprocess_image(image, label):
# Normalize pixels to the range [0, 1]
image = tf.cast(image, tf.float32) / 255.0
# Resize images to the desired size
image = tf.image.resize(image, image_size)
return image, label
To check your process_image function we have provided 4 images in the ./test_images/ folder:
The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.
# Load and preprocess the test image
image_path = './test_images/cautleya_spicata.jpg'
image = Image.open(image_path)
processed_image, _ = preprocess_image(image, None)
# Plot the original image and the processed image
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
axes[0].imshow(image)
axes[0].set_title('Original Image')
axes[0].axis('off')
axes[1].imshow(processed_image)
axes[1].set_title('Processed Image')
axes[1].axis('off')
plt.show()
Once you can get images in the correct format, it's time to write the predict function for making inference with your model.
Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:
probs, classes = predict(image_path, model, top_k)
If top_k=5 the output of the predict function should be something like this:
probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163 0.01541934 0.01452626 0.01443549 0.01407339]
> ['70', '3', '45', '62', '55']
Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.
Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.
def predict(image_path, model, top_k):
# Load and preprocess the image
image = Image.open(image_path)
processed_image, _ = preprocess_image(image, None)
processed_image = np.expand_dims(processed_image, axis=0)
# Predict the probabilities
predictions = model.predict(processed_image)
top_indices = np.argsort(predictions[0])[-top_k:][::-1]
top_indices_adjusted = [index + 1 for index in top_indices] # Adjust indices by adding 1
top_probabilities = predictions[0][top_indices]
# Get the class labels
label_map = json.load(open('label_map.json'))
classes = [label_map[str(index)] for index in top_indices_adjusted]
return top_probabilities, classes
It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:
In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:

You can convert from the class integer labels to actual flower names using class_names.
image_paths = ['./test_images/cautleya_spicata.jpg',
'./test_images/hard-leaved_pocket_orchid.jpg',
'./test_images/orange_dahlia.jpg',
'./test_images/wild_pansy.jpg']
for image_path in image_paths:
# Predict the probabilities and classes
probs, classes = predict(image_path, model, top_k=5)
# Load and preprocess the image
image = Image.open(image_path)
processed_image, _ = preprocess_image(image, None)
# Plot the image and the probabilities
fig, (ax1, ax2) = plt.subplots(figsize=(6, 8), nrows=2)
ax1.imshow(processed_image)
ax1.axis('off')
ax1.set_title('Input Image')
# Create a horizontal bar plot for the probabilities
y_pos = np.arange(len(classes))
ax2.barh(y_pos, probs, align='center', color='blue')
ax2.set_yticks(y_pos)
ax2.set_yticklabels(classes)
ax2.invert_yaxis()
ax2.set_xlabel('Probability')
ax2.set_title('Top 5 Predictions')
plt.tight_layout()
plt.show()
!pip uninstall -y markupsafe
!pip install markupsafe
!!jupyter nbconvert *.ipynb
!python predict.py ./test_images/orange_dahlia.jpg my_model.h5 --category_names label_map.json